iT邦幫忙

2023 iThome 鐵人賽

DAY 8
0

變數宣告

 📌 public $user;
     public $pass;
     public $dbname;
     public $db;
     public $field;

$user → 資料庫的使用者

$passr → 資料庫的密碼

$dbname → 資料庫名稱

$db → 資料表名稱

$field → 資料表的內容

連線資料庫

 📌 public function conn()
     {
       try
       {
         $pdo = new PDO("mysql:host=localhost;dbname=$this->dbname;
         charset=utf8",$this->user,$this->pass);
       }
       catch (PDOException $e)
       {
         throw new PDOException($e->getMessage());
       }
       return $pdo;
     }

新增

 📌 public function add($val)
     {
       $pdo = $this->conn();
       $sql = "INSERT INTO `". $this->db ."` VALUES" . $val;
       $sth = $pdo->prepare($sql);
       try
       {
         if (!($sth->execute($this->field)))
         {
           die( );
         }
       }
       catch (PDOException $e)
       {
         die( );
       }
       unset($pdo);
     }

SQL新增語法

 📌 INSERT INTO `USER` VALUES (’ ’,”alan”,”1996-02-07”)

查看

 📌 public function sel()
     {
       $pdo = $this->conn();
       $sql = "SELECT * FROM `". $this->db ."`";
       $stmt = $pdo->prepare($sql);
       $stmt->execute();
       $comments = array();
       try    
       {
         while($row = $stmt->fetch(PDO::FETCH_ASSOC))
         {
            array_push($comments, array(
            "id" => $row[$this->field[0]],
            "uid" => $row[$this->field[1]],
            "user" => $row[$this->field[2]]
            ));
         }
       }
       catch (PDOException $e)
       {
         die();
       }
       unset($pdo);
       return $comments;
     }

SQL查看語法

 📌 SELECT * FROM `USER`

輸出所有資料表的資料

 📌 $row = $stmt->fetch(PDO::FETCH_ASSOC)

$field 所存取的是資料表的欄位資訊

 📌 array_push($comments, array(
     "id" => $row[$this->field[0]],
     "uid" => $row[$this->field[1]],
     "user" => $row[$this->field[2]]
     ));

刪除

 📌 public function del($val , $id)
     {
        $pdo = $this->conn();
        $sql = "DELETE FROM`". $this->db ."` WHERE ". $val ." = ". $id;
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $comments = array();
        try
        {
          if (!($stmt->rowCount() > 0))
          {
            die();
          }
        }
        catch (PDOException $e)
        {
          die();
        }
        unset($pdo);
     }

SQL刪除語法

 📌 DELETE FROM `USER`  WHERE `uid` = “123”

使用範例

宣告

 📌 $sql = new sql( );
     $sql -> config("root"," ","shop","user");
     $sql -> put_data(["id","uid","name","password"]);

新增資料

 📌 $sql -> put_data(['','123','alan','123']);
     $sql -> add("(?,?,?,?)");

查看資料

 📌 $sql -> put_data(["id","uid","name","password"]);
     var_dump($sql -> sel());

刪除資料

 📌 $sql -> del("uid","123");

程式碼收錄:https://github.com/chyhhwen/shopping-system


上一篇
[DAY7]如何新增資料庫?
下一篇
[DAY9]如何網站路由化?
系列文
從前端到後端,設計出屬於自己的購物網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言